<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Example</title>
    <link rel="stylesheet" href="//cdn.bootcss.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
    <link rel="stylesheet" href="assets/css/chivoxsdk.css">
    <link rel="stylesheet" href="assets/css/chivox-example.css">
    <style>
        #changeParams input,#changeParams select{
            width: 173px;
            height: 30px;
        }
    </style>
</head>
<body>
<div>
    <nav class="navbar navbar-default">
        <div class="container-fluid">
            <div class="navbar-header">
                <p class="navbar-text">CHIVOX API JSSDK</p>
                <ul class="nav nav-pills">
                    <li><a href="index.html">首页</a></li>
                    <li><hr/></li>
                    <li class="active"><a href="index.html">基础应用场景</a></li>
                    <li><hr/></li>
                    <li><a href="player_tts.html">音频合成</a></li>
                    <li><hr/></li>
                    <li><a target="_blank" href="../doc/index.html">SDK接口文档</a></li>
                </ul>
            </div>
            <div class="content">
                <div class="chivoxpanel">
                    <div class="list">
                        <img class="icon" src="assets/img/eval.png"></img>
                        <p class="title">基础应用场景</p>
                        <ul>
                            <li class="active"><a href="index.html">英文句子评测</a></li>
                            <li><a href="player_tts.html">音频合成</a></li>
                            <li><a href="aiPanel.html">aiPanel</a></li>
                            <li> <a href="en_pred_exam.html">en_pred_exam</a></li>
                        </ul>
                    </div>
                    <div class="mainarea">
                        <p class="title">英文句子评测</p>
                        <textarea name="refText" id="currentWord" cols="90" rows="4"></textarea>
                        <div id="changeParams" style="line-height: 60px;">
                            <div>
                                coreType:<select name="coreTypes" id="coreType">
                                <!--<option value ="volvo"></option>-->
                            </select>
                                res:<select name="ress" id="res"></select>
                                userId: <input id="userId" type="text" value="chivox tester">
                            </div>

                        </div>
                        <div id="aiPanel" class="aiPanel">
                            <div>
                                <button class="play playOff"></button>
                                <button class="record recordOff"></button>
                                <button class="replay replayOff"></button>
                                <!-- <button class="changeWordButton">换个句子</button>-->
                                <div class="recordProgressBar"><div class="value"></div></div>
                            </div>
                            <div id="chivox-recorder"></div>
                        </div>
                        <!--  设置回放音量：<input type="range" min="0" max="100" id="inputButton">
                          获取录音音量：<input type="range" min="0" max="100" id="getMicButton">
                          设置录音音量：<input type="range" min="0" max="100" id="setMicButton">-->
                        <p class="scoreTitle">得分情况</p>
                        <p id="scoreResult">
                            发音得分：<span class="pron"></span>
                            <br/>
                            流利度：<span class="fluency"></span>
                            <br/>
                            详细得分：<span class="details"></span>
                        </p>
                    </div>
                </div>
            </div>
        </div>
    </nav>
</div>
<script src="//cdn.bootcss.com/jquery/1.12.4/jquery.min.js"></script>
<script src="../dist/chivox.umd.js"></script>
<script>


    $(function () {
        var config = getConfig();
        var coreTypeD = null;
        if(Object.keys(config).length >0){
            coreTypeD = Object.keys(config);
            setConfig(coreTypeD,"#coreType");
            setConfig(config[$("#coreType").val()].res,"#res");
        }

        $("#changeParams #coreType").on("change input",function () {
            setConfig(config[$("#coreType").val()].res,"#res");
            $("#currentWord").val(config[$("#coreType").val()].currentText);
        });

        $("#currentWord").val("I want to know the past and present of Hong Kong.");

        var recorder = new Html5Recorder({
            appKey: '14255202120000cf',
            sigurl: '../php/sig.php',
            micWatch:true, //默认值为false
            signature:function(){  //signature为function生效
                let data = null;
                $.ajax({  //ajax请求必须为同步模式
                    url: "../php/sig.php",
                    async:false,
                    type: 'POST',
                    dataType: 'json',
                    success: (json) => {
                        //签名服务返回数据必须为object，
                        // 且必须包含timestamp和sig字段,字段类型为string（数据格式如下）
                        // {sig: "cf502eb90300db899996dea1e6953f92"timestamp: "1577323026620"}
                        data = json
                    },
                    error: (err) => {

                    }
                });
                return data;
            },
            onInit: function (mess) {
                //初始化成功显示波形图
                recorder.showVolumeBar();
                console.log("on init")
            },
            onError: function (err) {
                console.log(JSON.stringify(err));
                if(err.id == 50003){
                    console.error("miWatch connect failed,please ckeck micWatch and reload")
                }
            }
        });

        var player = new Html5Player();

        $("#aiPanel .play").on("click",function () {
            if($("#aiPanel .play").hasClass("playOff")){
                playeven();
            }else{
                player.stop();
            }
        });

        function playeven(){
            player.load({
                url:"../static/I-want-to-know-the-past-and-present-of-Hong-Kong.mp3",
                success:function (code,message) {
                    player.play({
                        duration:2000,
                        onStop:function () {
                            console.log("player onStop");
                            controlPlayU(1)
                        },
                        onStart:function () {
                            console.log("player onStart");
                            controlPlayU(0)
                        }
                    })
                },
                error:function (err) {
                    console.log("player error:" + JSON.stringify(err));
                }
            })
        }

        $("#aiPanel .record").on("click",function () {
            if($(".record").hasClass("recordOff")){
                clearResult();
                recorder.record({
                    playDing:true,
                    // audioType:'mp3',
                    duration:60000,
                    serverParams:{
                        //  coreType:$("#coreType").val(),
                        coreType:"en.pred.exam",
                        // res: $("#changeParams #res").val(),
                        refText: $("#currentWord").val(),
                        rank: 100,
                        userId: $("#changeParams #userId").val(),
                        attachAudioUrl: 1,
                    },
                    onRecordIdGenerated:function (id) {
                        console.log("=============onRecordIdGenerated start=============");
                        console.log(JSON.stringify(id));
                        console.log("=============onRecordIdGenerated end=============");
                    },
                    onStart:function () {
                        controlRecordU(0)
                    },
                    onStop:function () {
                        controlRecordU(1)
                    },
                    onScore:function (e) {
                        var result = e.result ? e.result : null;
                        if(result){
                            $("#scoreResult .pron").html(result.pron);
                            $("#scoreResult .fluency").html(result.fluency.overall);
                            $("<pre>").text(JSON.stringify(e,null, 4)).appendTo("#scoreResult .details");
                        }
                    },
                    onInternalScore:function(data){
                        console.log("=============onInternalScore start=============");
                        console.log(JSON.stringify(data));
                        console.log("=============onInternalScore end=============");
                    },
                    onScoreError:function (err) {
                        alert(JSON.stringify(err));
                    }
                })
            }else if ($(".record").hasClass("recordOn")) {
                recorder.stopRecord();
            }
        });

        $("#aiPanel .replay").on("click",function () {
            if( !($("#aiPanel .replay").hasClass("replayDisabled"))){
                if($("#aiPanel .replay").hasClass("replayOff")){
                    recorder.startReplay({
                        onStop:function () {
                            console.log("replayStop");
                            controlReplayU(1)
                        }
                    });
                    controlReplayU(0)
                }else if($("#aiPanel .replay").hasClass("replayOn")){
                    recorder.stopReplay();
                }
            }
        });

        /*0 = > 开始录音 1 = > 结束录音 */
        function controlRecordU(state) {
            if(state == 0){
                $("#aiPanel .record").removeClass("recordOff")
                    .addClass("recordOn");
                $("#aiPanel .replay").addClass("replayDisabled");
            }else if(state == 1){
                $("#aiPanel .record").removeClass("recordOn")
                    .addClass("recordOff");
                $("#aiPanel .replay").removeClass("replayDisabled")
            }
        }

        function controlReplayU(state) {
            if(state == 0){
                $("#aiPanel .replay").removeClass("replayOff")
                    .addClass("replayOn");
            }else if(state == 1){
                $("#aiPanel .replay").removeClass("replayOn")
                    .addClass("replayOff");
            }
        }

        function controlPlayU(state) {
            if(state == 0){
                $("#aiPanel .play").removeClass("playOff")
                    .addClass("playOn");
            }else if(state == 1){
                $("#aiPanel .play").removeClass("playOn")
                    .addClass("playOff");
            }
        }

        function clearResult() {
            $("#scoreResult .pron").html("");
            $("#scoreResult .fluency").html("");
            $("#scoreResult .details").html("");
        }

        function getConfig() {
            var data = null;
            $.ajax({
                url: "./config/config.json",//这个就是请求地址对应sAjaxSource
                type: 'GET',
                dataType: 'json',
                async: false,
                success: function (result) {
                    data = result;
                    console.log(result)
                },
                error:function(err) {
                    alert("get config.json  fail:"+err)
                }
            });
            return data;
        }

        function setConfig(data,doms) {
            var str = "";
            if(data){
                for (var i = 0;i<data.length;i++){
                    str+="<option value ="+data[i]+">"+data[i]+"</option>"
                }
            }
            $(doms).html(str);
        }
    })
</script>
</body>
</html>